//#include "templates/HtmlTemplate.h"
#include "network/WebClient.h"
#include "network/MqttClient.h"
#include "network/WebServer.h"
#include "network/WifiConfig.h"

#define OTA_BUFFER_SIZE 4096
//ESP8266WebServer server(80);
//HtmlTemplate htmlTemplate;
GlobalConfig& config = GlobalConfig::getInstance();
WifiConfig  wifiConfig(config);
WebClient webClient(config);
WebServer webServer(config);
MqttClient mqttClient(config);

// 延迟时间（毫秒），可根据实际情况调整
const unsigned long delayTime = 2000;
unsigned int num =5;
// 记录开始时间
unsigned long startTime=millis();
void setup() {
////    初始化延迟1秒，防止系统为加载完成错误
    delay(delayTime);
    // 初始化看门狗
    EspClass::wdtEnable(GlobalConstants::WATCHDOG_TIMEOUT);
    Serial.begin(115200);
    pinMode(GlobalConstants::btn1Pin, INPUT_PULLUP);
    while (millis() - startTime < GlobalConstants::STARTUP_CHECK_TIME) {
        if (digitalRead(GlobalConstants::btn1Pin) == LOW) {
            num--;
            debugLog("btn1Pin is in low - level mode within LOW (%d) seconds after power - on\n",num);
        }else{
            debugLog("Waiting for initialization.\n");
        }
        if (num==0){
            break;
        }
        // // 可添加非阻塞处理逻辑
        delay(1000);
        // 可添加非阻塞处理逻辑
//        yield(); // 让出 CPU 时间片
    }

    debugLog("Initialization is complete. '%d' on\n",num);
    config.readConfig();
    if(num<1){
//        GlobalConstants::startWebConfig = true;
        webServer.setupWebServer();
    }else{
        pinMode(GlobalConstants::btn1Pin, OUTPUT);
        wifiConfig.tryConnectWiFi();
        GlobalConstants::appLoopStart=true;
    }

}
bool syncTimeState= false;
void loop() {
      // 喂狗
    EspClass::wdtFeed();
    if (WiFi.status() !=WL_CONNECTED) {
        GlobalConstants::wifiConnected = false;
    }else{
        GlobalConstants::wifiConnected = true;
        if (!syncTimeState){
            syncTime();
            syncTimeState=true;
        }
    }
        // 通电5秒后进入主逻辑，之前判断输入btn1Pin低电平 触发web配网服务
        webServer.loop();
        webClient.loop();
        mqttClient.loop();

        #ifdef DEBUG_ENABLED
    if (millis() - GlobalConstants::lastLogTime > GlobalConstants::LOG_INTERVAL) {
        debugLog("WIFI connected (state=%s) \n",GlobalConstants::wifiConnected?"ok":"not");
        GlobalConstants::lastLogTime = millis();
    }
        #endif
//    }
   delay(200);
    // delay(1000);
}